package com.limi.util;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;

/**
 * @author Limi Pan
 * @create 2018-09-12 上午10:09
 */
public class NashornSample {
    public static void main(String[] args) throws ScriptException, FileNotFoundException, NoSuchMethodException {
        String js = "E:\\IotProjects\\Java8\\src\\main\\resources\\script.js";
        String js2 = "E:\\IotProjects\\Java8\\src\\main\\resources\\script2.js";
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
//        engine.eval(new FileReader(js));
        engine.eval(new FileReader(js2));

//        Invocable invocable = (Invocable) engine;
//
//        // invoke fun1
//        Object result = invocable.invokeFunction("fun1", "Limi Pan");
//        System.out.println(result);
//        System.out.println(result.getClass());
//
//        // invoke fun2
//        invocable.invokeFunction("fun2", new Date());
//        invocable.invokeFunction("fun2", LocalDateTime.now());
//        invocable.invokeFunction("fun2", new Person());
    }

    public static String fun1(String name){
        System.out.format("Hi there from Java, %s", name);
        return "\ngreetings from Java";
    }
    public static void fun2(Object object){
        System.out.println(object.getClass());
    }
    public static void fun3(ScriptObjectMirror mirror){
        System.out.println(mirror.getClassName() + ":" +
                Arrays.toString(mirror.getOwnKeys(true)));
    }
    public static void fun4(ScriptObjectMirror person){
        System.out.println("Full Name is: " + person.callMember("getFullName"));
    }


}

class Person{
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}